from flask import Blueprint, render_template, request, redirect, url_for, flash, g, session
import sqlite3
# 从数据库工具模块导入，而非直接从app导入
from database import get_db

# 创建用户管理蓝图
user_bp = Blueprint('user', __name__, url_prefix='/users')

# 用户管理路由
@user_bp.route('/')
def user_management():
    db = get_db()
    search = request.args.get('search', '')
    
    if search:
        # 支持按用户名、姓名或邮箱搜索，使用LIKE实现模糊查询
        users = db.execute(
            'SELECT * FROM users WHERE username LIKE ? OR full_name LIKE ? OR email LIKE ?',
            ('%' + search + '%', '%' + search + '%', '%' + search + '%')
        ).fetchall()
    else:
        # 如果没有搜索关键词，查询所有用户
        users = db.execute('SELECT * FROM users').fetchall()
        
    return render_template('users.html', users=users)

# 添加用户路由
@user_bp.route('/add', methods=['GET', 'POST'])
def add_user():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        full_name = request.form['full_name']
        email = request.form['email']
        status = request.form['status']
        role = request.form['role']

        db = get_db()
        try:
            db.execute(
                'INSERT INTO users (username, password, full_name, email, status, role) VALUES (?, ?, ?, ?, ?, ?)',
                (username, password, full_name, email, status, role)
            )
            db.commit()
            flash('用户添加成功！', 'success')
            return redirect(url_for('user.user_management'))
        except sqlite3.IntegrityError:
            flash('用户名已存在！', 'danger')

    return render_template('add_user.html')

# 编辑用户路由
@user_bp.route('/edit/<int:id>', methods=['GET', 'POST'])
def edit_user(id):
    db = get_db()
    user = db.execute('SELECT * FROM users WHERE id = ?', (id,)).fetchone()

    if request.method == 'POST':
        full_name = request.form['full_name']
        email = request.form['email']
        status = request.form['status']
        role = request.form['role']

        db.execute(
            'UPDATE users SET full_name = ?, email = ?, status = ?, role = ? WHERE id = ?',
            (full_name, email, status, role, id)
        )
        db.commit()
        flash('用户更新成功！', 'success')
        return redirect(url_for('user.user_management'))

    return render_template('edit_user.html', user=user)

# 删除用户路由
@user_bp.route('/delete/<int:id>', methods=['POST'])
def delete_user(id):
    db = get_db()
    user = db.execute('SELECT * FROM users WHERE id = ?', (id,)).fetchone()
    
    if user is None:
        flash('用户不存在', 'danger')
    else:
        db.execute('DELETE FROM users WHERE id = ?', (id,))
        db.commit()
        flash('用户已删除！', 'success')
    
    return redirect(url_for('user.user_management'))


@user_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        db = get_db()
        user = db.execute('SELECT * FROM users WHERE username = ? AND password = ?', 
                         (username, password)).fetchone()
        
        if user:
            session['user_id'] = user['id']
            session['username'] = user['username']
            session['role'] = user['role']  # 添加这行保存用户角色
            flash('登录成功', 'success')
            return redirect(url_for('index'))
        else:
            flash('用户名或密码错误', 'danger')
    
    return render_template('login.html')

@user_bp.route('/change_password', methods=['GET', 'POST'])
def change_password():
    if 'user_id' not in session:
        return redirect(url_for('user.login'))
        
    if request.method == 'POST':
        # 处理密码修改逻辑
        old_password = request.form['old_password']
        new_password = request.form['new_password']
        confirm_password = request.form['confirm_password']
        
        db = get_db()
        user = db.execute('SELECT * FROM users WHERE id = ?', (session['user_id'],)).fetchone()
        
        if user['password'] != old_password:
            flash('原密码不正确', 'danger')
        elif new_password != confirm_password:
            flash('两次输入的新密码不一致', 'danger')
        else:
            db.execute('UPDATE users SET password = ? WHERE id = ?', 
                      (new_password, session['user_id']))
            db.commit()
            flash('密码修改成功', 'success')
            return redirect(url_for('user.user_management'))
            
    return render_template('change_password.html')

@user_bp.route('/logout')
def logout():
    session.clear()
    flash('您已成功登出', 'success')
    return redirect(url_for('user.login'))
    session.pop('user_id', None)
    flash('您已退出登录', 'info')
    return redirect(url_for('user.login'))